#ifdef _WIN32
#include <cppconn\exception.h>
#else
#include <cppconn/exception.h>
#endif
#include "ServerUtil.h"

ServerUtil::ServerUtil()
{
	config.load("app.properties");
}

/******************************************************************
************
* ++
* Method name 	: getInstance
* Description   : Get server utility instance
* Parameters    : none
*
* Global Variables
*    Accessed   : public static
*    Modified   : none
*
* Return values : a shared_ptr of server utility
*
* Modifications  : Endless love
* Description
*
* --
*******************************************************************
**********/
std::shared_ptr<ServerUtil> ServerUtil::getInstance()
{
	if (instance == nullptr)
	{
		instance = std::make_shared<ServerUtil>(ServerUtil());
	}

	return instance;
}

/******************************************************************
************
* ++
* Method name 	: isValidUser
* Description   : Check if login info of a user is valid
* Parameters    : connector: Connector to mysql service; user: User login info and output if loggin success
*
* Global Variables
*    Accessed   : none
*    Modified   : none
*
* Return values : true if login info is valid, false other else
*
* Modifications  : Endless love
* Description
*
* --
*******************************************************************
**********/
bool ServerUtil::isValidUser(MySql::MySqlConnector& connector, UserInfo& user)
{
	auto valid = false;
	// query from database and return result
	auto query = config.getProperty("checkLogin");
	query.replace(query.find('?'), 1, user.getUserName());
	query = query.replace(query.find('?'), 1, user.getPassword());
	auto result = connector.execQuery(query);
	valid = result != nullptr && result->rowsCount() == 1;

	if (valid)
	{
		result->next();
		try
		{
			// set user info out put
			user.setDisplayName(result->getString(config.getProperty("displayName"))); // set user display name
			user.setAge(result->getInt(config.getProperty("age")));
			user.setGrade(result->getString(config.getProperty("grade")));
		}
		catch (sql::SQLException & ex)
		{
			//	std::cerr << ex.what();
		}
	}

	delete result; // free resource

	return valid;
}

/******************************************************************
************
* ++
* Method name 	: getProperty
* Description   : Get property value base on it's key
* Parameters    : key: Key or peoperty, path before '=' symbol
*
* Global Variables
*    Accessed   : none
*    Modified   : none
*
* Return values : std::string
*
* Modifications  : Endless love
* Description
*
* --
*******************************************************************
**********/
std::string ServerUtil::getProperty(std::string key)
{
	return config.getProperty(key);
}

ServerUtil::~ServerUtil()
{}

std::shared_ptr<ServerUtil> ServerUtil::instance = nullptr;  // assign instance to nullptr
